const addball = function () {
  $("body").append(
    `
    <div class="ball miniball" id="ballBtn">
        <li class="arrow-right"></li><span>复制表格</span>
    </div>
    <div class="remodal" data-remodal-id="modal">
      <div class="pure-g" style="position: absolute;    top: 0px;    left: 0px;width:100%;">
        <div class="pure-u-1-4"><button data-remodal-action="close" class="remodal-close"></button></div>
        <div class="pure-u-3-4" style="display: flex;justify-content: flex-end;">
          <button class="button-warning pure-button pure-button-disabled" style="margin-right: 35px;">注意：数据少于3行的表格已隐藏。</button>
        </div>
      </div>
      <div id="_table_copy_table" style="display:none"></div>
      <div id="_table_copy_Container" style="width: 1024px; height: 500px;overflow-x:auto;overflow-y:auto;margin-top: 20px;padding-right: 20px;"></div>
    </div>  
   `
  );
  var inst = $("[data-remodal-id=modal]").remodal();
  $("#ballBtn").click(async () => {
    $("#_table_copy_Container").html(refindbtn + "<h1>数据优化加载中……</h1>");
    inst.open();
    const refindbtn = ``;
    let tables = JSON.parse(localStorage.getItem("_table_copy_"));
    const len = tables.length;
    let htmlStr = refindbtn;

    const dealtb = function (table, i) {
      return new Promise(async (resolve, reject) => {
        const tag = table.tag;

        const count = await db.getIndexCount("tables", "table", tag);

        if (count < 4) reject("");

        const front = await db.getAllMatching("tables", {
          index: "table",
          query: IDBKeyRange.only(tag),
          count: 2,
        });

        const last = await db.getAllMatching("tables", {
          index: "table",
          query: IDBKeyRange.only(tag),
          count: 1,
          direction: "prev",
        });

        const rows = front.concat(last);

        htmlStr +=
          "<div class='copy_table_div' style=''><div class='copy_table_div_1st' style=''><table class='pure-table pure-table-bordered' style='width:99%;margin-top:10px;'>";
        if (rows.length >= 3) {
          htmlStr += rows[0].row;
          htmlStr += rows[1].row;
          htmlStr += rows[rows.length - 1].row;
        } else {
          rows.forEach((r) => {
            htmlStr += r.row;
          });
        }
        htmlStr += "</table></div>";
        htmlStr += `<div class="pure-g" style="margin-top:2px;"><div class="pure-u-1-4" style="text-align:left;margin-top:10px">
        ${
          i + 1
        }/${len}</div><div class="pure-u-3-4" style="display: flex;justify-content: flex-end;">
        <button class="button-secondary pure-button copy_table_load_buttons" stat="0" index="${i}">加载数据</button>
        <button class="button-secondary pure-button copy_table_hide_buttons" stat="1">隐藏本表数据</button>
        <button class="button-secondary pure-button copy_table_cut_buttons" index="${i}" style="margin-left:-2px;display:none;">C</button>
        <button class="button-secondary pure-button copy_table_hide_others_buttons" stat="1">隐藏其他表格</button>
        <button class="button-success pure-button copy_table_buttons" index="${i}">复制表格(共${count}行)</button>
        <button class='pure-button button-success text_copy copy_table_buttons' index="${i}" style="margin-left:-2px" >A</button></div></div></div>`;
        // console.log(i);
        // $("#_table_copy_Container").html(htmlStr);
        resolve(i);
      });
    };

    let i = 0;
    for (const tb of tables) {
      await dealtb(tb, i).catch((e) => {});
      i++;
    }
    $("#_table_copy_Container").html(htmlStr);
    if (tables.length == 0) {
      $("#_table_copy_Container").html(
        refindbtn + "<h1>没有可以复制的表格</h1>"
      );
    }
    inst.open();
  });
  $("#ballBtn").hover(
    () => {
      $("#ballBtn").removeClass("miniball");
      $("#ballBtn").addClass("normalball");
    },
    () => {
      $("#ballBtn").removeClass("normalball");
      $("#ballBtn").addClass("miniball");
    }
  );
  initball();
  $(document).ready(function () {
    let rows;
    let k = -1;
    new ClipboardJS(".copy_table_buttons", {
      text: function (trigger) {
        const i = parseInt($(trigger).attr("index"));
        console.log(i, k);
        if (i !== k) return "";
        let htmlStr = "<table>";
        for (const r of rows) {
          htmlStr += r.row;
        }
        htmlStr += "</table>";
        if ($(trigger).hasClass("text_copy")) {
          htmlStr = htmlToExcel(htmlStr);
        } else {
          $(trigger).text("复制成功");
        }
        return htmlStr;
      },
    });
    $(document).on("click", ".copy_table_load_buttons", async function () {
      $(".copy_table_div .copy_table_load_buttons").text("加载数据");
      rows = [];
      k = -1;
      const i = parseInt($(this).attr("index"));
      let tables = JSON.parse(localStorage.getItem("_table_copy_"));
      rows = await db.getAllMatching("tables", {
        index: "table",
        query: IDBKeyRange.only(tables[i].tag),
      });
      k = i;
      $(this).text("加载完成");
    });
    $(document).on("click", ".copy_table_hide_others_buttons", function () {
      let div = $(this).closest(".copy_table_div");
      let stat = $(this).attr("stat");
      if (stat == "1") {
        $(this).attr("stat", 0);
        $(this).text("显示其他表格");
      } else {
        $(this).attr("stat", 1);
        $(this).text("隐藏其他表格");
      }
      $(div).nextAll().toggle();
      $(div).prevAll().toggle();
    });
    $(document).on("click", ".copy_table_cut_buttons", function () {
      const i = parseInt($(this).attr("index"));
      let tables = JSON.parse(localStorage.getItem("_table_copy_"));
      tables[i].rowcount = 0;
      tables[i].rows = [];
      tables[i].rowtags = [];
      localStorage.setItem("_table_copy_", JSON.stringify(tables));
      $("#ballBtn").click();
    });
    $(document).on("click", ".copy_table_hide_buttons", function () {
      let div = $(this).closest(".copy_table_div");
      let stat = $(this).attr("stat");
      if (stat == "1") {
        $(this).attr("stat", 0);
        $(this).text("显示本表数据");
      } else {
        $(this).attr("stat", 1);
        $(this).text("隐藏本表数据");
      }
      $(div).find("tr :not(:first)").toggle();
      const mainContainer = $("#_table_copy_Container");
      const scrollToContainer = $(this);
      mainContainer.scrollTop(
        scrollToContainer.offset().top -
          mainContainer.offset().top +
          mainContainer.scrollTop() -
          200
      );
    });
  });
};
